<template>
  <div class="settings">
  <label>
    <input type="checkbox" v-model="enableWheelNavigation" />
    启用滚轮切换帖子
  </label>
</div>
  <div class="post-detail">
    <!-- 页面头部 -->
    <header class="header">
      <button @click="router.back()" class="back"> ← 返回 </button>
    </header>

    <!-- 作者信息 -->
    <section class="author-section">
      <img class="avatar" :src="post.author_avatar || defaultAvatar" alt="作者头像" />
      <div class="author-info">
        <h3>{{ post.username }}</h3>
        <p>{{ post.formattedTime }}</p>
      </div>
    </section>

    <!-- 文字内容 -->
    <section class="post-body">
      <h2>{{ post.title }}</h2>
      <!-- 资源查看器 -->
      <div class="media-viewer">
        <div class="media-container" v-if="post.media && post.media.length > 0">
          <div
            class="media-slider"
            ref="mediaSlider"
            :style="{ transform: `translateX(-${currentIndex * 100}%)` }"
          >
            <div
              v-for="(media, index) in post.media"
              :key="index"
              class="media-item"
              :class="{ active: currentIndex === index }"
              @click="currentIndex = index"
            >
              <img 
                v-if="media.type === 'image'" 
                :src="media.url" 
                alt="Media"
              />
              <video v-if="media.type === 'video'" :src="media.url" controls></video>
            </div>
          </div>
          <div class="media-controls" v-if="post.media.length > 1">
            <button @click="prevMedia" class="prev">‹</button>
            <button @click="nextMedia" class="next">›</button>
          </div>
        </div>
        <p v-else class="no-media">暂无媒体资源</p>
      </div>
      <p class="content" v-html="post.content"></p>
    </section>

    <!-- 操作区 -->
     <section class="actions">
      <button @click="likePost" :class="{ liked:isLiked }">
        {{ isLiked ? '❤️' : '🤍' }} {{ post.likes }}
      </button>
    </section>

    <!-- 评论区 -->
    <section class="comments">
      <h3>评论</h3>
      <div v-if="comments.length === 0">暂无评论</div>
      <ul>
        <li v-for="c in comments" :key="c.id">
          <img class="comment-avatar" :src="c.avatar || defaultAvatar" alt="评论者头像" />
          <div>
            <strong>{{ c.username }}</strong>
            <p>{{ c.content }}</p>
            <span class="time">{{ c.formattedTime }}</span>
          </div>
        </li>
      </ul>
      <div class="comment-box">
        <input v-model="newComment" placeholder="发表评论..." />
        <button @click="submitComment">发送</button>
      </div>
    </section>
    <div v-if="isLoading" class="loading">加载中...</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick,onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from '@/utils/request';

const route = useRoute();
const router = useRouter();
const postId = Number(route.params.id);
const enableWheelNavigation = ref(true);

const post = ref<any>({
  id: 0,
  title: '',
  content: '',
  cover_url: '',
  likes: 0,
  timestamp: '',
  username: '',
  author_avatar: '',
  media: [],
  formattedTime: ''
});
const comments = ref<any[]>([]);
const newComment = ref("");
const defaultAvatar = "";
const currentIndex = ref(0);
const mediaSlider = ref<HTMLDivElement | null>(null);
const isLoading = ref(true);
const isLiked = ref(false);
const isScrolling = ref(false);
const scrollDebounceTime = ref(300); // 防抖时间（毫秒）
const currentPostId = ref(postId);

// 存储帖子ID列表（假设从API获取）
const postIds = ref<number[]>([]);
// 格式化时间戳
function formatTime(timestamp: string) {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

async function fetchPost() {
  isLoading.value = true;
  try {
    const res = await api.get(`/content/post/${postId}`);
    console.log(res);

    if (res.post) {
      const postData = res.post;
      
      // 处理media字段（假设后端返回的是文件名）
      postData.media = postData.media || [];
      console.log(postData.media)
      const mediaArray = JSON.parse(postData.media)

      // 格式化媒体URL（假设后端域名是http://localhost:5000）
      postData.media = mediaArray.map(media => {
        if (media.type === 'image' && media.filename) {
          return {
            ...media,
            url: `http://192.168.10.130:5000/get/media/${media.filename}`
          };
        } else if (media.type === 'video' && media.filename) {
          return {
            ...media,
            url: `http://192.168.10.130:5000/get/media/${media.filename}`
          };
        }
        return media;
      });
      
      // 格式化时间戳
      postData.formattedTime = formatTime(postData.timestamp);
      
      // 设置author_avatar默认值
      postData.author_avatar = postData.author_avatar || defaultAvatar;
      
      post.value = postData;
      comments.value = res.comments || [];
      
      // 格式化评论时间
      comments.value.forEach(comment => {
        comment.formattedTime = formatTime(comment.timestamp);
        comment.avatar = comment.avatar || defaultAvatar;
      });
      
      // 模拟点赞状态（实际需从接口获取）
      isLiked.value = false;
    }
  } catch (err) {
    console.error("获取帖子失败", err);
  } finally {
    isLoading.value = false;
  }
}
async function fetchPostIds() {
  try {
    const res = await api.get('/content/posts/ids');
    postIds.value = res.data || [];
  } catch (err) {
    console.error('获取帖子ID列表失败', err);
  }
}

// 处理滚轮事件
function handleWheel(event: WheelEvent) {
    if (!enableWheelNavigation.value) return;

  event.preventDefault();
  
  if (!postIds.value.length) return;
  
  const currentIndex = postIds.value.findIndex(id => id === currentPostId.value);
  if (currentIndex === -1) return;
  
  if (event.deltaY > 0) {
    // 向下滚动：跳转到下一个帖子
    const nextIndex = currentIndex + 1;
    if (nextIndex < postIds.value.length) {
      router.push(`/post/${postIds.value[nextIndex]}`);
    }
  } else {
    // 向上滚动：跳转到上一个帖子
    const prevIndex = currentIndex - 1;
    if (prevIndex >= 0) {
      router.push(`/post/${postIds.value[prevIndex]}`);
    }
  }
}

onMounted(() => {
  fetchPost();
  fetchPostIds();
  
  // 绑定全局滚轮事件
  window.addEventListener('wheel', handleWheel);
});

onUnmounted(() => {
  // 移除滚轮事件监听，避免内存泄漏
  window.removeEventListener('wheel', handleWheel);
});
async function likePost() {
  try {
    const res = await api.post(`/content/post/${postId}/like`);
    if (res.likes !== undefined) {
      post.value.likes = res.likes;
      isLiked.value = !isLiked.value;
      
      // 添加点赞成功的提示（可选）
      const message = isLiked.value ? '点赞成功' : '已取消点赞';
      console.log(message);
      // 可以在这里添加Toast提示
    }
  } catch (err) {
    console.error("点赞失败", err);
    // 错误提示
  }
}

async function submitComment() {
  if (!newComment.value.trim()) return;
  try {
    const res = await api.post(`/content/post/${postId}/comment`, {
      content: newComment.value
    });
    if (res.msg === "评论成功") {
      newComment.value = "";
      fetchPost();
    }
  } catch (err) {
    console.error("提交评论失败", err);
  }
}

function nextMedia() {
  if (currentIndex.value < post.value.media.length - 1) {
    currentIndex.value++;
  }
}

function prevMedia() {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  }
}

onMounted(() => {
  fetchPost();
  nextTick(() => {
    if (mediaSlider.value) {
      mediaSlider.value.addEventListener('wheel', (event) => {
        const mediaLength = post.value.media.length;
        if (mediaLength <= 1) return;
        
        event.preventDefault(); // 显式设置passive: false后可安全调用
        
        if (event.deltaY > 0) {
          if (currentIndex.value < mediaLength - 1) {
            currentIndex.value++;
          }
        } else {
          if (currentIndex.value > 0) {
            currentIndex.value--;
          }
        }
      }, { passive: false });
    }
  });
});
</script>


<style scoped>
.post-detail {
  max-width: 600px;
  margin: 40px auto;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-family: 'PingFang SC', sans-serif;
  position: relative;
}
.header .back {
  color: #ff2d55;
  background: none;
  border: none;
  font-size: 16px;
}
.author-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
}
.author-info h3 {
  margin: 0;
  font-size: 16px;
}
.author-info p {
  margin: 0;
  font-size: 12px;
  color: #666;
}
.post-body {
  margin-top: 20px;
}
.post-body h2 {
  font-size: 20px;
  margin-bottom: 15px;
  font-weight: 600;
}
.post-body .media-viewer {
  position: relative;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}
.post-body .media-container {
  overflow: hidden;
}
.post-body .media-slider {
  display: flex;
  transition: transform 0.3s ease;
  height: 300px;
}
.post-body .media-item {
  min-width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}
.post-body .media-item img, 
.post-body .media-item video {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
.post-body .media-item.active {
  opacity: 1;
}
.post-body .media-controls {
  position: absolute;
  top: 50%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  transform: translateY(-50%);
  z-index: 10;
}
.post-body .media-controls button {
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 50%;
  font-size: 16px;
}
.post-body .content {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin-top: 10px;
}
.actions button {
  background: #ff2d55;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 16px;
  margin-top: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}
.actions button.liked {
  color: #ff8ba7;
  background: transparent;
  border: 1px solid #ff8ba7;
}
.comments {
  margin-top: 40px;
}
.comments h3 {
  font-size: 18px;
  margin-bottom: 15px;
  position: relative;
  padding-bottom: 10px;
}
.comments h3::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 40px;
  height: 3px;
  background: #ff2d55;
}
.comments ul {
  list-style: none;
  padding: 0;
}
.comments li {
  display: flex;
  gap: 10px;
  margin: 15px 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
.comment-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
.comment-box {
  display: flex;
  margin-top: 20px;
  align-items: center;
}
.comment-box input {
  flex: 1;
  padding: 6px 10px;
  border-radius: 20px;
  border: 1px solid #ccc;
  height: 36px;
  font-size: 14px;
}
.comment-box button {
  background: #ff2d55;
  color: white;
  border: none;
  padding: 6px 16px;
  margin-left: 10px;
  border-radius: 20px;
  height: 36px;
  cursor: pointer;
}
.time {
  font-size: 12px;
  color: #888;
  display: block;
  margin-top: 5px;
}
.no-media {
  text-align: center;
  color: #888;
  padding: 20px 0;
  font-size: 14px;
}
.loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  font-size: 18px;
  color: #ff2d55;
}
</style>